<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <TreeTools
          :node-data="company"
          :is-root="true"
          @addDepartment="addDepartment"
        />
        <!-- 分割线 -->
        <hr />
        <!-- 以下是部门数据 -->
        <el-tree :data="depts" :props="{ label: 'name' }" default-expand-all>
          <template #default="scope">
            <TreeTools
              :node-data="scope.data"
              @delDepartment="getDepartmentList"
              @addDepartment="addDepartment"
              @editDepartment="editDepartment"
            />
          </template>
        </el-tree>
      </el-card>
      <!-- :node-data对标父传子给add-dept组件中的props中nodeData -->
      <!-- 换言之就是add-dept组件中的props中nodeData 是用来接收newDate的 -->
      <AddDept
        ref="addDept"
        :show-dialog.sync="showDialog"
        :node-data="newDate"
        @addDept="getDepartmentList"
      ></AddDept>
    </div>
  </div>
</template>

<script>
import TreeTools from "./components/tree-tools.vue";
import AddDept from "./components/add-dept.vue";
import { getDepartmentList } from "@/api/departments";
import { listToTreeData } from "@/utils/index";
export default {
  components: {
    TreeTools,
    AddDept,
  },
  data() {
    return {
      company: {
        name: "江苏传智播客教育科技股份有限公司",
        manager: "负责人",
        id: "",
      },
      depts: [],
      showDialog: false,
      newDate: {},
    };
  },
  created() {
    this.getDepartmentList();
  },
  methods: {
    async getDepartmentList() {
      const { depts } = await getDepartmentList();
      // this.depts = depts;

      this.depts = listToTreeData(depts, "");

      // const newData = listToTreeData(depts, "");
      // console.dir(newData);
    },

    // 添加部门
    // 此时传来的参数node=子组件tree-tools中的 this.nodeData
    addDepartment(node) {
      // 将树形点击时传入的数据记录下来传给弹窗
      this.newDate = node;
      this.showDialog = true;
    },

    // 编辑部门
    async editDepartment(nodeData) {
      // 这是是树形被点击,确定要编辑的部门了
      // 弹出弹窗, 同时回显数据也应该在这时候执行
      // 可以利用 $refs 拿到子组件, 然后直接调用其中的函数
      await this.$refs.addDept.getDepartDetail(nodeData.id);
      this.newDate = nodeData;
      this.showDialog = true;
    },
  },
};
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
.optBtn {
  cursor: pointer;
}
</style>
